<template>
  <div class="app-container">
    <!-- 顶部筛选区域 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" class="filter-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="能耗类型">
              <el-radio-group v-model="filterForm.energyType" @change="handleEnergyTypeChange">
                <el-radio-button label="电耗" />
                <el-radio-button label="水耗" />
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="计量点选择">
              <el-select v-model="filterForm.meterPointId" placeholder="请选择计量点" clearable
                @change="handleMeterPointChange">
                <el-option v-for="item in meterPointOptions" :key="item.meterPointId" :label="item.pointName"
                  :value="item.meterPointId">
                  <template #default>
                    <span>{{ item.pointName }}</span>
                    <el-tooltip effect="dark" placement="right">
                      <template #content>{{ item.pointDesc }}</template>
                      <el-icon size="14" class="ml-1">
                        <InfoFilled />
                      </el-icon>
                    </el-tooltip>
                  </template>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" :shortcuts="dateShortcuts"
                @change="handleDateChange" clearable />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="4">
            <el-form-item class="action-buttons">
              <el-button type="primary" @click="refreshData">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 关键指标区域 -->
    <!-- <el-row :gutter="20" class="mt-2">
      <el-col :xs="12" :sm="8" :md="4">
        <el-card>
          <div class="metric-card">
            <div class="metric-title">总消耗量</div>
            <div class="metric-value">
              {{ currentData.consumption ? currentData.consumption.toFixed(2) : 0 }}
              <span class="unit">{{ unitLabel }}</span>
            </div>
            <div class="metric-compare">
              {{ filterForm.dateRange ? `${filterForm.dateRange[0]}至${filterForm.dateRange[1]}` : '全部时间' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="8" :md="4">
        <el-card>
          <div class="metric-card">
            <div class="metric-title">平均单价</div>
            <div class="metric-value">
              {{ currentData.unitPrice ? currentData.unitPrice.toFixed(4) : 0 }}
              <span class="unit">元/{{ unitLabel }}</span>
            </div>
            <div class="metric-compare">
              <el-button size="mini" text @click="showPriceEditDialog = true" v-if="filterForm.meterPointId">
                编辑
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="8" :md="4">
        <el-card>
          <div class="metric-card">
            <div class="metric-title">总金额</div>
            <div class="metric-value">
              ¥{{ currentData.amount ? currentData.amount.toFixed(2) : 0 }}
            </div>
            <div class="metric-compare">自动计算</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="8" :md="4">
        <el-card>
          <div class="metric-card">
            <div class="metric-title">同比变化率</div>
            <div class="metric-value" :class="getRateClass(currentData.同比变化率)">
              {{ currentData.同比变化率 || '--' }}
            </div>
            <div class="metric-compare">较上年同期</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="8" :md="4">
        <el-card>
          <div class="metric-card">
            <div class="metric-title">环比变化率</div>
            <div class="metric-value" :class="getRateClass(currentData.环比变化率)">
              {{ currentData.环比变化率 || '--' }}
            </div>
            <div class="metric-compare">较上月同期</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="8" :md="4">
        <el-card>
          <div class="metric-card">
            <div class="metric-title">状态</div>
            <div class="metric-value" :class="currentData.hasException ? 'exception' : 'normal'">
              <el-icon v-if="currentData.hasException">
                <WarningFilled />
              </el-icon>
              <el-icon v-else>
                <Check />
              </el-icon>
              {{ currentData.hasException ? '异常' : '正常' }}
            </div>
            <div class="metric-compare">
              <span v-if="currentData.hasException">
                消耗量同比涨幅超15%
              </span>
              <span v-else>
                数据正常
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row> -->

    <!-- 能耗趋势分析 -->
    <el-card class="mt-2">
      <el-row :gutter="20" justify="space-between" align="middle">
        <el-col>
          <h3>
            {{ filterForm.meterPointId ? currentMeterName : '全部计量点' }} {{ filterForm.energyType }}趋势分析
          </h3>
        </el-col>
        <el-col>
          <el-radio-group v-model="filterForm.timeDimension" @change="handleTimeDimensionChange">
            <el-radio-button :value="1">按日</el-radio-button>
            <el-radio-button :value="2">按月</el-radio-button>
            <el-radio-button :value="3">按年</el-radio-button>
          </el-radio-group>
        </el-col>
      </el-row>
      <div class="chart-container">
        <ECharts :option="trendChartOption" style="height: 400px;" />
      </div>
    </el-card>

    <!-- 能耗明细表格 -->
    <el-card class="mt-2">
      <div slot="header">
        <h3>
          {{ filterForm.meterPointId ? currentMeterName : '全部计量点' }} {{ filterForm.energyType }}明细
        </h3>
      </div>
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="occurDate" label="日期" align="center" />
        <el-table-column prop="pointName" label="计量点名称" align="center" />
        <el-table-column prop="consumption" label="消耗量" align="center">
          <template #default="{ row }">
            {{ row.consumption.toFixed(2) }} {{ unitLabel }}
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价(元)" align="center">
          <template #default="{ row }">
            {{ row.unitPrice.toFixed(4) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额(元)" align="center">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="同比变化率" label="同比变化" align="center">
          <template #default="{ row }">
            <span :class="getRateClass(row.同比变化率)">
              {{ row.同比变化率 || '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="环比变化率" label="环比变化" align="center">
          <template #default="{ row }">
            <span :class="getRateClass(row.环比变化率)">
              {{ row.环比变化率 || '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="异常标记" label="状态" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.hasException" class="exception-icon">
              <WarningFilled />
            </el-icon>
            <el-icon v-else class="normal-icon">
              <Check />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination mt-3">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize"
          :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </el-card>

    <!-- 单价编辑弹窗 -->
    <el-dialog v-model="showPriceEditDialog" title="修改单价" width="30%">
      <el-form :model="priceForm" label-width="80px">
        <el-form-item label="当前单价">
          <el-input v-model.number="priceForm.unitPrice" :precision="4" placeholder="请输入单价" />
          <div class="text-xs text-gray-500 mt-1">
            单位：元/{{ unitLabel }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPriceEditDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmPriceChange">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import {
  Refresh,
  InfoFilled,
  WarningFilled,
  Check
} from '@element-plus/icons-vue'
import ECharts from '@/components/ECharts'
import {
  getMeterPoints,
  getEnergyDetail,
  updateEnergyPrice,
  getEnergyTrend
} from '@/api/prod_operate/synthesis/cost/energy_detail'
import { ElMessage } from 'element-plus'

// 筛选表单
const filterForm = ref({
  energyType: '电耗', // 电耗/水耗
  meterPointId: '', // 非必填
  dateRange: [], // 非必填
  timeDimension: 1 // 1-日 2-月 3-年
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '近7天',
    onClick(picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '近30天',
    onClick(picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  }
]

// 计量点选项
const meterPointOptions = ref([])

// 当前选中计量点的数据
const currentData = ref({})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页控制
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 趋势图配置
const trendChartOption = ref({})

// 单价编辑弹窗
const showPriceEditDialog = ref(false)
const priceForm = ref({
  unitPrice: 0
})

// 当前计量点名称
const currentMeterName = ref('')

// 根据能耗类型获取单位标签
const unitLabel = computed(() => {
  return filterForm.value.energyType === '电耗' ? 'kWh' : 'm³'
})

// 初始化数据
const initData = async () => {
  try {
    // 不设置默认日期，允许为空
    await fetchMeterPoints()
    // 初始加载汇总数据（不选计量点和日期）
    await fetchAllData()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败，请刷新页面重试')
  }
}

// 获取计量点列表
const fetchMeterPoints = async () => {
  try {
    const res = await getMeterPoints(filterForm.value.energyType)
    meterPointOptions.value = res || []
  } catch (error) {
    console.error('获取计量点列表失败:', error)
    ElMessage.error('获取计量点列表失败')
  }
}

// 获取所有数据
const fetchAllData = async () => {
  try {
    // 并行请求数据
    await Promise.all([
      fetchCurrentData(),
      fetchEnergyTrendData(),
      fetchTableData()
    ])
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 获取当前数据（支持空日期和空计量点）
const fetchCurrentData = async () => {
  try {
    const params = {
      energyType: filterForm.value.energyType
    }
    // 仅当有值时传递参数
    if (filterForm.value.meterPointId) {
      params.meterPointId = filterForm.value.meterPointId
      // 更新当前计量点名称
      const selectedMeter = meterPointOptions.value.find(
        item => item.meterPointId === filterForm.value.meterPointId
      )
      currentMeterName.value = selectedMeter ? selectedMeter.pointName : ''
    } else {
      currentMeterName.value = '全部计量点'
    }
    if (filterForm.value.dateRange?.length) {
      params.startDate = filterForm.value.dateRange[0]
      params.endDate = filterForm.value.dateRange[1]
    }

    const res = await getEnergyDetail(params)
    currentData.value = res.rows || {}
    priceForm.value.unitPrice = currentData.value.unitPrice || 0
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 获取趋势图数据（支持空日期）
const fetchEnergyTrendData = async () => {
  try {
    const timeTypeMap = { 1: 'day', 2: 'month', 3: 'year' }
    const params = {
      energyType: filterForm.value.energyType,
      timeType: timeTypeMap[filterForm.value.timeDimension]
    }
    // 仅当有值时传递参数
    if (filterForm.value.meterPointId) {
      params.meterPointId = filterForm.value.meterPointId
    }
    if (filterForm.value.dateRange?.length) {
      params.startDate = filterForm.value.dateRange[0]
      params.endDate = filterForm.value.dateRange[1]
    }

    const res = await getEnergyTrend(params)
    const data = res || []
    updateTrendChart(data)
  } catch (error) {
    console.error('获取趋势图数据失败:', error)
    ElMessage.error('获取趋势图数据失败')
  }
}

// 更新趋势图表
const updateTrendChart = (data) => {
  trendChartOption.value = {
    title: {
      text: `${filterForm.value.meterPointId ? currentMeterName.value : '全部计量点'} ${filterForm.value.energyType}趋势分析`
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function (params) {
        const param = params[0]
        return `${param.name}<br/>${param.seriesName}: ${param.value.toFixed(2)} ${unitLabel.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.occurDate)
    },
    yAxis: {
      type: 'value',
      name: `消耗量(${unitLabel.value})`,
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: filterForm.value.energyType,
        type: 'line',
        data: data.map(item => item.amount),
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(54, 162, 235, 0.4)'
            }, {
              offset: 1, color: 'rgba(54, 162, 235, 0)'
            }]
          }
        }
      }
    ]
  }
}

// 获取表格数据（支持空日期）
const fetchTableData = async () => {
  try {
    loading.value = true
    const params = {
      energyType: filterForm.value.energyType,
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }
    // 仅当有值时传递参数
    if (filterForm.value.meterPointId) {
      params.meterPointId = filterForm.value.meterPointId
    }
    if (filterForm.value.dateRange?.length) {
      params.startDate = filterForm.value.dateRange[0]
      params.endDate = filterForm.value.dateRange[1]
    }

    const res = await getEnergyDetail(params)
    tableData.value = res.rows || []
    pagination.value.total = res.total || 0
  } catch (error) {
    console.error('获取表格数据失败:', error)
    ElMessage.error('获取表格数据失败')
  } finally {
    loading.value = false
  }
}

// 处理能耗类型变化
const handleEnergyTypeChange = async () => {
  meterPointOptions.value = []
  filterForm.value.meterPointId = ''
  await fetchMeterPoints()
  await fetchAllData()
}

// 处理计量点变化
const handleMeterPointChange = async () => {
  await fetchAllData()
}

// 处理日期变化
const handleDateChange = () => {
  fetchAllData()
}

// 处理时间维度变化
const handleTimeDimensionChange = () => {
  fetchEnergyTrendData()
}

// 刷新数据
const refreshData = () => {
  pagination.value.currentPage = 1
  fetchAllData()
  ElMessage.success('数据已刷新')
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  fetchTableData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchTableData()
}

// 确认修改单价
const confirmPriceChange = async () => {
  try {
    if (!currentData.value.energyId) return

    await updateEnergyPrice({
      energyId: currentData.value.energyId,
      newPrice: priceForm.value.unitPrice
    })

    showPriceEditDialog.value = false
    await fetchCurrentData()
    await fetchTableData()
    ElMessage.success('单价更新成功')
  } catch (error) {
    console.error('更新单价失败:', error)
    ElMessage.error('更新单价失败')
  }
}

// 获取变化率样式类
const getRateClass = (rate) => {
  if (!rate) return ''
  if (rate.startsWith('+')) return 'positive'
  if (rate.startsWith('-')) return 'negative'
  return ''
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.mt-2 {
  margin-top: 20px !important;
}

.mt-3 {
  margin-top: 30px !important;
}

.metric-card {
  text-align: center;
  padding: 20px 0;
}

.metric-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.metric-value .unit {
  font-size: 16px;
  color: #606266;
}

.metric-compare {
  font-size: 12px;
  color: #909399;
}

.positive {
  color: #f56c6c;
}

.negative {
  color: #409eff;
}

.exception {
  color: #f56c6c;
}

.normal {
  color: #67c23a;
}

.chart-container {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}

.pagination {
  text-align: right;
}

.exception-icon {
  color: #f56c6c;
}

.normal-icon {
  color: #67c23a;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
  padding-top: 5px;
}
</style>
<style scoped>
.el-card :deep(.el-form-item) {
  margin-bottom: 0px;
}
</style>